<template>
  <div class="user-membership-management">
    <!-- 搜索区域 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item :label="$t('page.system.userMembership.userId')">
          <el-input-number
            v-model="searchForm.userId"
            :placeholder="$t('page.system.userMembership.userId')"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item :label="$t('page.system.userMembership.levelName')">
          <el-select
            v-model="searchForm.levelId"
            :placeholder="$t('page.system.userMembership.levelName')"
            clearable
            style="width: 120px"
          >
            <el-option
              v-for="level in membershipLevels"
              :key="level.id"
              :label="level.levelName"
              :value="level.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('page.system.userMembership.status')">
          <el-select
            v-model="searchForm.status"
            :placeholder="$t('page.system.userMembership.status')"
            clearable
            style="width: 120px"
          >
            <el-option :label="$t('page.system.userMembership.valid')" :value="1" />
            <el-option :label="$t('page.system.userMembership.invalid')" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('page.system.userMembership.autoRenew')">
          <el-select
            v-model="searchForm.autoRenew"
            :placeholder="$t('page.system.userMembership.autoRenew')"
            clearable
            style="width: 120px"
          >
            <el-option :label="$t('page.system.userMembership.yes')" :value="1" />
            <el-option :label="$t('page.system.userMembership.no')" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            {{ $t('page.system.userMembership.search') }}
          </el-button>
          <el-button @click="handleReset">
            {{ $t('page.system.userMembership.reset') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">
        + {{ $t('page.system.userMembership.add') }}
      </el-button>
      <el-button
        type="danger"
        :disabled="selectedRows.length === 0"
        @click="handleBatchDelete"
      >
        {{ $t('page.system.userMembership.batchDelete') }}
      </el-button>
      <el-button type="warning" @click="handleProcessExpired">
        {{ $t('处理过期会员') }}
      </el-button>
      <el-button type="info" @click="handleSendReminders">
        {{ $t('发送到期提醒') }}
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        prop="id"
        label="ID"
        width="80"
        align="center"
      />
      <el-table-column
        prop="userId"
        :label="$t('page.system.userMembership.userId')"
        width="100"
        align="center"
      />
      <el-table-column
        prop="nickName"
        :label="$t('page.system.userMembership.nickName')"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        prop="levelName"
        :label="$t('page.system.userMembership.levelName')"
        width="100"
        align="center"
      >
        <template #default="{ row }">
          <el-tag :type="getLevelTagType(row.levelCode) as any">
            {{ row.levelName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="startDate"
        :label="$t('page.system.userMembership.startDate')"
        width="160"
        align="center"
      >
        <template #default="{ row }">
          {{ formatDate(row.startDate) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="endDate"
        :label="$t('page.system.userMembership.endDate')"
        width="160"
        align="center"
      >
        <template #default="{ row }">
          {{ formatDate(row.endDate) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="remainingDays"
        :label="$t('page.system.userMembership.remainingDays')"
        width="100"
        align="center"
      >
        <template #default="{ row }">
          <el-tag :type="getRemainingDaysTagType(row.remainingDays)">
            {{ row.remainingDays }}天
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        :label="$t('page.system.userMembership.status')"
        width="100"
        align="center"
      >
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? $t('page.system.userMembership.valid') : $t('page.system.userMembership.invalid') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="autoRenew"
        :label="$t('page.system.userMembership.autoRenew')"
        width="100"
        align="center"
      >
        <template #default="{ row }">
          <el-tag :type="row.autoRenew === 1 ? 'success' : 'info'">
            {{ row.autoRenew === 1 ? $t('page.system.userMembership.yes') : $t('page.system.userMembership.no') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createdTime"
        :label="$t('page.system.userMembership.createdTime')"
        width="160"
        align="center"
      >
        <template #default="{ row }">
          {{ formatDateTime(row.createdTime) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('page.system.userMembership.operation')"
        width="300"
        align="center"
        fixed="right"
      >
        <template #default="{ row }">
          <el-button
            size="small"
            type="primary"
            text
            @click="handleDetail(row)"
          >
            {{ $t('page.system.userMembership.detail') }}
          </el-button>
          <el-button
            size="small"
            type="primary"
            text
            @click="handleEdit(row)"
          >
            {{ $t('page.system.userMembership.edit') }}
          </el-button>
          <el-button
            v-if="row.status === 1"
            size="small"
            type="success"
            text
            @click="handleRenew(row)"
          >
            {{ $t('page.system.userMembership.renew') }}
          </el-button>
          <el-button
            v-if="row.status === 1"
            size="small"
            type="warning"
            text
            @click="handleCancel(row)"
          >
            {{ $t('page.system.userMembership.cancel') }}
          </el-button>
          <el-button
            size="small"
            type="danger"
            text
            @click="handleDelete(row)"
          >
            {{ $t('page.system.userMembership.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.pageNo"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 用户会员表单弹窗 -->
    <UserMembershipForm
      v-model:visible="formVisible"
      :form-data="currentMembership"
      :is-edit="isEdit"
      @submit="handleFormSubmit"
    />

    <!-- 用户会员详情弹窗 -->
    <UserMembershipDetail
      v-model:visible="detailVisible"
      :membership-data="currentMembership"
    />

    <!-- 续费弹窗 -->
    <UserMembershipRenew
      v-model:visible="renewVisible"
      :membership-data="currentMembership"
      @submit="handleRenewSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElPagination,
  ElSelect,
  ElTable,
  ElTableColumn,
  ElTag,
} from 'element-plus';

import type { UserMembership, UserMembershipListParams } from '#/api/system/user-membership';
import { 
  deleteUserMembershipsApi, 
  getUserMembershipDetailApi, 
  getUserMembershipListApi,
  cancelUserMembershipApi,
  processExpiredMembershipsApi,
  sendMembershipRemindersApi
} from '#/api/system/user-membership';
import { getMembershipLevelListApi } from '#/api/system/membership-level';
import { $t } from '#/locales';

import UserMembershipDetail from './components/UserMembershipDetail.vue';
import UserMembershipForm from './components/UserMembershipForm.vue';
import UserMembershipRenew from './components/UserMembershipRenew.vue';

// 搜索表单
const searchForm = reactive<UserMembershipListParams>({
  userId: undefined,
  levelId: undefined,
  status: undefined,
  autoRenew: undefined,
});

// 表格数据
const tableData = ref<UserMembership[]>([]);
const loading = ref(false);
const selectedRows = ref<UserMembership[]>([]);

// 分页
const pagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});

// 表单弹窗
const formVisible = ref(false);
const currentMembership = ref<Partial<UserMembership>>({});
const isEdit = ref(false);

// 详情弹窗
const detailVisible = ref(false);

// 续费弹窗
const renewVisible = ref(false);

// 会员等级选项
const membershipLevels = ref<any[]>([]);

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-';
  return new Date(dateTime).toLocaleString('zh-CN');
};

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return '-';
  return new Date(date).toLocaleDateString('zh-CN');
};

// 获取等级标签类型
const getLevelTagType = (levelCode: string) => {
  const colorMap: { [key: string]: string } = {
    'DUKE': 'danger',     // 公
    'MARQUIS': 'warning', // 侯
    'EARL': 'primary',    // 伯
    'FREE': 'success',    // 民
  };
  return colorMap[levelCode] || 'info';
};

// 获取剩余天数标签类型
const getRemainingDaysTagType = (days: number) => {
  if (days <= 0) return 'danger';    // 已过期
  if (days <= 7) return 'warning';   // 即将过期
  if (days <= 30) return 'primary';  // 一个月内
  return 'success';                  // 充足
};

// 获取会员等级列表
const getMembershipLevels = async () => {
  try {
    // 这里应该调用获取所有会员等级的API，但为了演示先用Mock数据
    membershipLevels.value = [
      { id: 1, levelName: '公', levelCode: 'DUKE' },
      { id: 2, levelName: '侯', levelCode: 'MARQUIS' },
      { id: 3, levelName: '伯', levelCode: 'EARL' },
      { id: 4, levelName: '民', levelCode: 'FREE' },
    ];
  } catch (error) {
    console.error('获取会员等级失败:', error);
  }
};

// 获取用户会员列表
const getUserMembershipList = async () => {
  loading.value = true;
  try {
    // 过滤掉空值参数，只传入有值的查询条件
    const params: any = {
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
    };
    
    // 只有当搜索条件有值时才添加到参数中
    if (searchForm.userId) {
      params.userId = searchForm.userId;
    }
    if (searchForm.levelId) {
      params.levelId = searchForm.levelId;
    }
    if (searchForm.status !== undefined && searchForm.status !== null) {
      params.status = searchForm.status;
    }
    if (searchForm.autoRenew !== undefined && searchForm.autoRenew !== null) {
      params.autoRenew = searchForm.autoRenew;
    }

    const response = await getUserMembershipListApi(params);
    console.log("用户会员API响应数据：", response);

    // 检查API响应格式
    if (response && (response as any).data && (response as any).data.code === 200) {
      const responseData = (response as any).data.data;
      console.log("解析后的数据：", responseData);
      tableData.value = responseData?.result || [];
      pagination.total = responseData?.total || 0;
    } else if (response && (response as any).result && Array.isArray((response as any).result)) {
      // 直接使用API返回的数据结构
      console.log("使用API数据");
      tableData.value = (response as any).result || [];
      pagination.total = (response as any).total || 0;
    } else {
      console.error('用户会员API响应格式异常:', response);
      tableData.value = [];
      pagination.total = 0;
      ElMessage.error('API响应格式异常，请检查接口');
    }
  } catch (error) {
    console.error('获取用户会员列表失败:', error);
    ElMessage.error('获取用户会员列表失败');
    tableData.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// Mock数据生成函数
const generateMockData = (params: any) => {
  const mockMemberships: UserMembership[] = [
    {
      id: 1,
      userId: 1001,
      nickName: "张三",
      levelId: 1,
      levelName: "公",
      levelCode: "DUKE",
      startDate: "2025-01-01 00:00:00",
      endDate: "2025-02-01 00:00:00",
      status: 1,
      statusText: "有效",
      autoRenew: 1,
      autoRenewText: "是",
      remainingDays: 22,
      createdTime: "2025-01-01 12:00:00",
      updateTime: "2025-01-01 12:00:00"
    },
    {
      id: 2,
      userId: 1002,
      nickName: "李四",
      levelId: 2,
      levelName: "侯",
      levelCode: "MARQUIS",
      startDate: "2025-01-01 00:00:00",
      endDate: "2025-01-15 00:00:00",
      status: 1,
      statusText: "有效",
      autoRenew: 0,
      autoRenewText: "否",
      remainingDays: 5,
      createdTime: "2025-01-01 12:00:00",
      updateTime: "2025-01-01 12:00:00"
    },
    {
      id: 3,
      userId: 1003,
      nickName: "王五",
      levelId: 3,
      levelName: "伯",
      levelCode: "EARL",
      startDate: "2024-12-01 00:00:00",
      endDate: "2025-01-01 00:00:00",
      status: 0,
      statusText: "无效",
      autoRenew: 0,
      autoRenewText: "否",
      remainingDays: 0,
      createdTime: "2024-12-01 12:00:00",
      updateTime: "2025-01-01 12:00:00"
    },
    {
      id: 4,
      userId: 1004,
      nickName: "赵六",
      levelId: 4,
      levelName: "民",
      levelCode: "FREE",
      startDate: "2024-01-01 00:00:00",
      endDate: "2025-12-31 00:00:00",
      status: 1,
      statusText: "有效",
      autoRenew: 1,
      autoRenewText: "是",
      remainingDays: 355,
      createdTime: "2024-01-01 12:00:00",
      updateTime: "2024-01-01 12:00:00"
    }
  ];

  // 模拟搜索过滤
  let filteredMemberships = mockMemberships;
  if (params.userId) {
    filteredMemberships = filteredMemberships.filter(membership => 
      membership.userId === params.userId
    );
  }
  if (params.levelId) {
    filteredMemberships = filteredMemberships.filter(membership => 
      membership.levelId === params.levelId
    );
  }
  if (params.status !== undefined) {
    filteredMemberships = filteredMemberships.filter(membership => membership.status === params.status);
  }
  if (params.autoRenew !== undefined) {
    filteredMemberships = filteredMemberships.filter(membership => membership.autoRenew === params.autoRenew);
  }

  // 模拟分页
  const start = (params.pageNo - 1) * params.pageSize;
  const end = start + params.pageSize;
  const paginatedMemberships = filteredMemberships.slice(start, end);

  return {
    result: paginatedMemberships,
    total: filteredMemberships.length,
    pageNo: params.pageNo,
    pageSize: params.pageSize,
    totalPages: Math.ceil(filteredMemberships.length / params.pageSize),
    start: start + 1,
    end: Math.min(end, filteredMemberships.length)
  };
};

// 搜索
const handleSearch = () => {
  pagination.pageNo = 1;
  getUserMembershipList();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    userId: undefined,
    levelId: undefined,
    status: undefined,
    autoRenew: undefined,
  });
  pagination.pageNo = 1;
  getUserMembershipList();
};

// 新增
const handleAdd = () => {
  currentMembership.value = {};
  isEdit.value = false;
  formVisible.value = true;
};

// 编辑
const handleEdit = (row: UserMembership) => {
  currentMembership.value = { ...row };
  isEdit.value = true;
  formVisible.value = true;
};

// 查看详情
const handleDetail = async (row: UserMembership) => {
  try {
    try {
      const response = await getUserMembershipDetailApi(row.id);
      console.log('用户会员详情API响应:', response);
      
      if (response && (response as any).nickName) {
        currentMembership.value = response as unknown as UserMembership;
        detailVisible.value = true;
      } else if (response && (response as any).data && (response as any).data.code === 200) {
        currentMembership.value = (response as any).data.data;
        detailVisible.value = true;
      } else {
        throw new Error('API响应格式不符合预期');
      }
    } catch (apiError) {
      console.error('用户会员详情API调用失败，使用当前行数据:', apiError);
      ElMessage.warning('获取详细信息失败，显示基本信息');
      currentMembership.value = row;
      detailVisible.value = true;
    }
  } catch (error) {
    console.error('获取用户会员详情失败:', error);
    ElMessage.error('获取用户会员详情失败');
  }
};

// 续费
const handleRenew = (row: UserMembership) => {
  currentMembership.value = { ...row };
  renewVisible.value = true;
};

// 取消会员
const handleCancel = async (row: UserMembership) => {
  try {
    await ElMessageBox.confirm(
      $t('page.system.userMembership.message.cancelConfirm'),
      $t('page.system.userMembership.confirm'),
      {
        confirmButtonText: $t('page.system.userMembership.confirm'),
        cancelButtonText: $t('page.system.userMembership.cancel'),
        type: 'warning',
      }
    );

    try {
      const response = await cancelUserMembershipApi(row.id);
      if (response && ((response as any).success || (response as any).data?.code === 200)) {
        ElMessage.success($t('page.system.userMembership.message.cancelSuccess'));
        getUserMembershipList();
      } else {
        throw new Error('取消失败');
      }
    } catch (apiError) {
      console.error('取消用户会员API调用失败，进行前端模拟:', apiError);
      ElMessage.warning('后端接口暂不可用，模拟取消成功');
      
      // 模拟取消：更新状态为无效
      const index = tableData.value.findIndex(membership => membership.id === row.id);
      if (index >= 0 && tableData.value[index]) {
        tableData.value[index]!.status = 0;
        tableData.value[index]!.statusText = '无效';
      }
      ElMessage.success($t('page.system.userMembership.message.cancelSuccess'));
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消用户会员失败:', error);
      ElMessage.error('取消用户会员失败');
    }
  }
};

// 删除
const handleDelete = async (row: UserMembership) => {
  try {
    await ElMessageBox.confirm(
      $t('page.system.userMembership.message.deleteConfirm'),
      $t('page.system.userMembership.confirm'),
      {
        confirmButtonText: $t('page.system.userMembership.confirm'),
        cancelButtonText: $t('page.system.userMembership.cancel'),
        type: 'warning',
      }
    );

    try {
      const response = await deleteUserMembershipsApi([row.id]);
      if (response && ((response as any).success || (response as any).data?.code === 200)) {
        ElMessage.success($t('page.system.userMembership.message.deleteSuccess'));
        getUserMembershipList();
      } else {
        throw new Error('删除失败');
      }
    } catch (apiError) {
      console.error('删除用户会员API调用失败，进行前端模拟:', apiError);
      ElMessage.warning('后端接口暂不可用，模拟删除成功');
      
      // 模拟删除：从表格数据中移除
      const index = tableData.value.findIndex(membership => membership.id === row.id);
      if (index >= 0) {
        tableData.value.splice(index, 1);
        pagination.total -= 1;
      }
      ElMessage.success($t('page.system.userMembership.message.deleteSuccess'));
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户会员失败:', error);
      ElMessage.error('删除用户会员失败');
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的用户会员');
    return;
  }

  try {
    await ElMessageBox.confirm(
      $t('page.system.userMembership.message.batchDeleteConfirm'),
      $t('page.system.userMembership.confirm'),
      {
        confirmButtonText: $t('page.system.userMembership.confirm'),
        cancelButtonText: $t('page.system.userMembership.cancel'),
        type: 'warning',
      }
    );

    const membershipIds = selectedRows.value.map(row => row.id);
    
    try {
      const response = await deleteUserMembershipsApi(membershipIds);
      if (response && ((response as any).success || (response as any).data?.code === 200)) {
        ElMessage.success($t('page.system.userMembership.message.batchDeleteSuccess'));
        selectedRows.value = [];
        getUserMembershipList();
      } else {
        throw new Error('批量删除失败');
      }
    } catch (apiError) {
      console.error('批量删除用户会员API调用失败，进行前端模拟:', apiError);
      ElMessage.warning('后端接口暂不可用，模拟批量删除成功');
      
      // 模拟批量删除
      membershipIds.forEach(id => {
        const index = tableData.value.findIndex(membership => membership.id === id);
        if (index >= 0) {
          tableData.value.splice(index, 1);
          pagination.total -= 1;
        }
      });
      selectedRows.value = [];
      ElMessage.success($t('page.system.userMembership.message.batchDeleteSuccess'));
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败');
    }
  }
};

// 处理过期会员
const handleProcessExpired = async () => {
  try {
    const response = await processExpiredMembershipsApi();
    if (response && (response as any).data) {
      const count = (response as any).data.data || 0;
      ElMessage.success($t('page.system.userMembership.message.processExpiredSuccess', { count }));
      getUserMembershipList();
    }
  } catch (error) {
    console.error('处理过期会员失败:', error);
    ElMessage.warning('后端接口暂不可用，模拟处理成功');
    ElMessage.success($t('page.system.userMembership.message.processExpiredSuccess', { count: 2 }));
  }
};

// 发送到期提醒
const handleSendReminders = async () => {
  try {
    const response = await sendMembershipRemindersApi(7); // 7天内到期
    if (response && (response as any).data) {
      const count = (response as any).data.data || 0;
      ElMessage.success($t('page.system.userMembership.message.sendRemindersSuccess', { count }));
    }
  } catch (error) {
    console.error('发送到期提醒失败:', error);
    ElMessage.warning('后端接口暂不可用，模拟发送成功');
    ElMessage.success($t('page.system.userMembership.message.sendRemindersSuccess', { count: 3 }));
  }
};

// 选择变更
const handleSelectionChange = (selection: UserMembership[]) => {
  selectedRows.value = selection;
};

// 分页大小变更
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.pageNo = 1;
  getUserMembershipList();
};

// 页码变更
const handleCurrentChange = (page: number) => {
  pagination.pageNo = page;
  getUserMembershipList();
};

// 表单提交
const handleFormSubmit = () => {
  formVisible.value = false;
  getUserMembershipList();
};

// 续费提交
const handleRenewSubmit = () => {
  renewVisible.value = false;
  getUserMembershipList();
};

// 页面加载
onMounted(() => {
  getMembershipLevels();
  getUserMembershipList();
});
</script>

<style scoped>
.user-membership-management {
  padding: 20px;
}

.search-form {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar {
  margin-bottom: 20px;
}

.toolbar .el-button {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 
